<template>
	<Page>
		<Topbar hideMenu />
		<Content>
			<Panel>
				<view class="left">
					<Info :data="workInfo" :state="state" :dataNumber="workNumberInfo"
						backUrl="/pages/workbench/productionNew/index" @openCuttingPlan="openCuttingPlan" />
				</view>
				<view class="right">
					<view style="padding-bottom: 15px;">
						<u-row justify="space-between">
							<u-col span="5">
								<view class="line-search">
									<view class="serch-line" style="width: 14rem;">
										班次时间
									</view>
									<DatePicker v-model="model.shiftTime" @change="shiftTimeChange" />
								</view>
							</u-col>
							<u-col span="5">
								<view class="line-search">
									<view class="serch-line">
										班次
									</view>
									<SingleSelect @change="shiftChange" v-model="model.shiftId" :list="shifts"
										mode="single" />
								</view>

							</u-col>
						</u-row>
					</view>
					<!-- 加载状态 -->
					<view v-if="loading" class="loading-container">
						<uni-load-more status="loading"></uni-load-more>
					</view>

					<!-- 四个图表区域 -->
					<view v-else class="charts-container">
						<!-- 工单计划概览 -->
						<view class="chart-item">
							<view class="chart-left">
								<view class="chart-title">工单计划概览</view>
								<view class="chart-qiun-data-charts">
									<qiun-data-charts ref="chart1" type="ring" :chartData="chartData1" :opts="opts1" />
								</view>
							</view>
							<view class="chart-right">
								<view class="chart-legend">
									<view class="legend-item">
										<view class="legend-color" style="background-color:#A5EF52;"></view>
										<view class="legend-text">
											<text class="legend-label">计划数量</text>
											<text class="legend-value">{{chartData.planQuantity || 0}}</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #4095E5;"></view>
										<view class="legend-text">
											<text class="legend-label">已报工数量</text>
											<text class="legend-value">{{chartData.reportQuantity || 0}}</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #6AC5C5;"></view>
										<view class="legend-text">
											<text class="legend-label">未报工数量</text>
											<text class="legend-value">{{chartData.unReportQuantity || 0}}</text>
										</view>
									</view>
								</view>
								<view class="percentage-text">
									<text class="percentage-label">计划数量达成率</text>
									<text class="percentage-value">{{chartData.planAchievementRate || 0}}%</text>
								</view>
							</view>
						</view>
						<!-- 稼动率概览 -->
						<view class="chart-item">
							<view class="chart-left">
								<view class="chart-title">稼动率概览</view>
								<view class="chart-qiun-data-charts">
									<qiun-data-charts ref="chart2" type="ring" :chartData="chartData2" :opts="opts2" />
								</view>
							</view>
							<view class="chart-right">
								<view class="chart-legend">
									<view class="legend-item">
										<view class="legend-color" style="background-color:#A5EF52;"></view>
										<view class="legend-text">
											<text class="legend-label">计划开机时长</text>
											<text class="legend-value">{{chartData.planOpenTime || 0}}h</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #4095E5;"></view>
										<view class="legend-text">
											<text class="legend-label">实际开机时长</text>
											<text class="legend-value">{{chartData.actualOpenTime || 0}}h</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #6AC5C5;"></view>
										<view class="legend-text">
											<text class="legend-label">异常停机时长</text>
											<text class="legend-value">{{chartData.errorStopTime || 0}}h</text>
										</view>
									</view>
								</view>
								<view class="percentage-text">
									<text class="percentage-label">时间稼动率</text>
									<text class="percentage-value">{{chartData.timeUtilizationRate || 0}}%</text>
								</view>
								<view class="percentage-text" style="margin-top: 0rem;">
									<text class="percentage-label">OEE</text>
									<text class="percentage-value">{{chartData.oee || 0}}%</text>
								</view>
							</view>
						</view>
						<!-- 当班报工概览 -->
						<view class="chart-item">
							<view class="chart-left">
								<view class="chart-title">当班报工概览</view>
								<view class="chart-qiun-data-charts">
									<qiun-data-charts ref="chart3" type="ring" :chartData="chartData3" :opts="opts3" />
								</view>
							</view>
							<view class="chart-right">
								<view class="chart-legend">
									<view class="legend-item">
										<view class="legend-color" style="background-color:#A5EF52;"></view>
										<view class="legend-text">
											<text class="legend-label">理论班产能</text>
											<text class="legend-value">{{chartData.theoryCapacity || 0}}</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #4095E5;"></view>
										<view class="legend-text">
											<text class="legend-label">合格品数量</text>
											<text class="legend-value">{{chartData.passCount || 0}}</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #6AC5C5;"></view>
										<view class="legend-text">
											<text class="legend-label">不良品数量</text>
											<text class="legend-value">{{chartData.failCount || 0}}</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #BD3124;"></view>
										<view class="legend-text">
											<text class="legend-label">报废品数量</text>
											<text class="legend-value">{{chartData.scrapCount || 0}}</text>
										</view>
									</view>
								</view>
								<view class="percentage-text">
									<text class="percentage-label">当班合格率</text>
									<text class="percentage-value">{{chartData.passRate || 0}}%</text>
								</view>
								<view class="percentage-text" style="margin-top: 0rem;">
									<text class="percentage-label">班产能达成率</text>
									<text class="percentage-value">{{chartData.capacityRate || 0}}%</text>
								</view>
							</view>
						</view>
						<!-- 当班投料概览 -->
						<view class="chart-item" @click="showFeedingCount">
							<view class="chart-left">
								<view class="chart-title">当班投料概览</view>
								<view class="chart-qiun-data-charts">
									<qiun-data-charts ref="chart4" type="column" :chartData="chartData4"
										:opts="opts4" />
								</view>
							</view>
							<view class="chart-right">
								<view class="chart-legend">
									<view class="legend-item">
										<view class="legend-color" style="background-color:#A5EF52;"></view>
										<view class="legend-text">
											<text class="legend-label">理论投料数量</text>
											<text
												class="legend-value">{{chartData.theoryCurrentFeedingCount || 0}}</text>
										</view>
									</view>
									<view class="legend-item">
										<view class="legend-color" style="background-color: #4095E5;"></view>
										<view class="legend-text">
											<text class="legend-label">实际投料数量</text>
											<text class="legend-value">{{chartData.feedingCount || 0}}</text>
										</view>
									</view>
								</view>
								<view class="percentage-text">
									<text class="percentage-label">生产利用率</text>
									<text class="percentage-value">{{chartData.produceRate || 0}}%</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 按钮组 -->
					<view class="btn-group">
						<view class="btn-item btn-primary" @click="startWork" v-if="workInfo.state === '下发'">
							<text>开工</text>
						</view>
						<view class="btn-item btn-success" @click="open3" v-if="workInfo.state === '生产'">
							<text>中断</text>
						</view>
						<view class="btn-item btn-default" @click="openMaterial" v-if="workInfo.state === '生产'">
							<text>物料操作</text>
						</view>
						<view class="btn-item btn-default" @click="openReport" v-if="workInfo.state === '生产'">
							<text>生产提报</text>
						</view>
						<view class="btn-item btn-default" @click="openScrap" v-if="workInfo.state === '生产'">
							<text>自检报废</text>
						</view>
						<view class="btn-item btn-default" @click="openShutdown" v-if="workInfo.state === '生产'">
							<text>异常停机</text>
						</view>
						<view class="btn-item btn-default" @click="toClear" v-if="workInfo.state === '完成'">
							<text>清线</text>
						</view>
						<view class="btn-item btn-danger" @click="open2" v-if="workInfo.state === '生产'">
							<text>完成</text>
						</view>
						<view class="btn-item btn-success" @click="open4" v-if="workInfo.state === '中断'">
							<text>恢复</text>
						</view>
					</view>
				</view>
			</Panel>
		</Content>
		<Modal title="确认开始吗？" ref="popup1" @confirm="confirm1" />
		<Modal title="确认完成吗" ref="popup2" @confirm="confirm2" />
		<Modal title="确认中断吗？" ref="popup3" @confirm="confirm3" />
		<Modal title="请选择中断原因" ref="popup3" @confirm="confirm3">
			<uni-data-select v-model="interruptReason" label="中断原因" :modelValue="interruptReason"
				:localdata="interruptReasons" format="{label}" placeholder="请选择" :clear="false"></uni-data-select>
		</Modal>
		<Modal title="确认恢复吗？" ref="popup4" @confirm="confirm4" />
		<ModalCuttingPlan ref="modalCuttingPlan" @openModalPrintLabel="openModalPrintLabel"></ModalCuttingPlan>
		<ModalPrintLabel ref="modalPrintLabel" :labelTypes="[{label: '条料标签',value: '条料标签'}]"></ModalPrintLabel>

		<!-- 投料详情弹框 -->
		<Modal title="当班投料详情" ref="feedingModal" width="80%" noComfirm>
			<view class="table-demo">
				<Table ref="table" :columns="feedingColumns" :table-data="workNumberInfo.currentFeedingList || []"
					:pagination="false" :tooltip="false">
				</Table>
			</view>
		</Modal>
		<Modal title="开工扫码验证" ref="startWorkScanModal" width="85%" :noClose="true" :noComfirm="true">
			<view class="scan-form">
				<view class="form-item">
					<view class="form-label">设备码</view>
					<view class="form-input-group">
						<input type="text" v-model="deviceCode" placeholder="请扫描设备码" class="form-input"
							@confirm="validateDeviceCode" />
						<uni-icons type="scan" @click="scanDeviceCode" size="25" style="margin-left: 5rpx;"></uni-icons>
					</view>

					<view class="validation-result" v-if="deviceCodeValidated !== null">
						<text v-if="deviceCodeValidated" class="valid">✓ 验证通过</text>
						<text v-else class="invalid">✗ 验证失败，请重新扫描</text>
					</view>
				</view>

				<view class="form-item">
					<view class="form-label">模具码</view>
					<view class="form-input-group">
						<input type="text" v-model="moldCode" placeholder="请扫描模具码" class="form-input"
							@confirm="validateMoldCode" />
						<uni-icons type="scan" @click="scanMoldCode" size="25" style="margin-left: 5rpx;"></uni-icons>
					</view>
					<view class="validation-result" v-if="moldCodeValidated !== null">
						<text v-if="moldCodeValidated" class="valid">✓ 验证通过</text>
						<text v-else class="invalid">✗ 验证失败，请重新扫描</text>
					</view>
				</view>

				<view class="custom-buttons">
					<view class="cancel-btn" @click="cancelScan">取消</view>
					<view class="confirm-btn" v-if="showConfirmButton" @click="confirm1">确认开工</view>
				</view>
			</view>
		</Modal>
	</Page>
</template>

<script>
	import Page from "@/components/page/index.vue";
	import Topbar from "@/components/topbar/index.vue";
	import Content from "@/components/content/index.vue";
	import Panel from "@/components/panel/index.vue";
	import Button from "@/components/button/index.vue";
	import Info from "@/components/info/indexNew.vue";
	import Modal from '@/components/modal/index.vue';
	import ModalCuttingPlan from '@/components/operate/modal-material-cutting-plan/index.vue';
	import ModalPrintLabel from '@/components/operate/modal-print-label/index.vue';
	import {
		timeIsBetweenTimeRange
	} from "@/utils/date";
	import filter from "@/utils/filter";
	import fetch from "@/utils/fetch";
	import Table from '@/components/table/index.vue';
	import SingleSelect from '@/components/formField/singleSelect/index.vue';
	import DatePicker from '@/components/formField/datePicker/index.vue';
	import {
		getDevice
	} from "@/store/user.js";

	export default {
		components: {
			Page,
			Topbar,
			Content,
			Panel,
			Info,
			Table,
			Button,
			Modal,
			DatePicker,
			SingleSelect,
			ModalCuttingPlan,
			ModalPrintLabel
		},
		data() {
			return {
				moldCode: null,
				deviceCode: null,
				deviceCodeValidated: null, // null: 未验证, true: 验证通过, false: 验证失败
				moldCodeValidated: null,
				showConfirmButton: false,
				shifts: [],
				model: {
					shiftTime: new Date().getTime(),
					shiftId: null
				},
				pageInfo: {},
				loading: true, // 新增加载状态
				feedingColumns: [{
						label: '物料编码',
						value: 'materialCode'
					},
					{
						label: '物料名称',
						value: 'materialName'
					},
					{
						label: '重量',
						value: 'weight'
					},
					{
						label: '理论重量',
						value: 'theoryWeight'
					},
					{
						label: '单位',
						value: 'unit'
					}
				],
				showStart: false,
				interruptReasons: [],
				interruptReason: '',
				workInfo: {
					state: '',
					workCode: '',
					cuttingPlanCode: ''
				},
				workNumberInfo: {
					currentFeedingList: [],
					historyFeedingList: [],
					passCount: 0,
					failCount: 0,
					scrapCount: 0
				},
				chartData: {
					planQuantity: 0,
					reportQuantity: 0,
					unReportQuantity: 0,
					planAchievementRate: 0,
					planOpenTime: 0,
					actualOpenTime: 0,
					errorStopTime: 0,
					timeUtilizationRate: 0,
					oee: 0,
					theoryCapacity: 0,
					passCount: 0,
					failCount: 0,
					scrapCount: 0,
					passRate: 0,
					capacityRate: 0,
					theoryCurrentFeedingCount: 0,
					feedingCount: 0,
					produceRate: 0,
					currentFeedingList: []
				},
				maxMaterialNameLength: 4,
				materialNameEllipsis: '...',
				// 图表1数据：工单计划概览
				chartData1: {
					series: [{
						data: [{
								name: "已报工数量",
								value: 0
							},
							{
								name: "未报工数量",
								value: 0
							}
						],
					}]
				},
				// 图表2数据：稼动率
				chartData2: {
					series: [{
						data: [{
								name: "实际开工时长",
								value: 0
							},
							{
								name: "异常停机时长",
								value: 0
							}
						],
					}]
				},
				// 图表3数据：当班报工
				chartData3: {
					series: [{
						data: [{
								name: "合格品数量",
								value: 0
							},
							{
								name: "不良品数量",
								value: 0
							},
							{
								name: "报废品数量",
								value: 0
							}
						],
						color: []
					}]
				},
				// 图表4数据：当班投料
				chartData4: {
					categories: [],
					series: [{
							name: "理论投料量",
							type: "bar",
							data: [],
							color: "#A5EF52"
						},
						{
							name: "实际投料量",
							type: "bar",
							data: [],
							color: "#4095E5"
						}
					]
				},
				// 工单计划概览配置
				opts1: {
					update: true,
					color: ["#4095E5", "#6AC5C5", '#BD3124'],
					dataLabel: false,
					legend: {
						show: false
					},
					title: {
						show: false,
						name: '',
						fontSize: 0
					},
					subtitle: {
						show: false,
						name: '',
						fontSize: 0
					},
					extra: {
						pie: {
							ringWidth: 50,
							radius: 40,
							label: {
								show: false,
								line: false,
								position: 'outer'
							}
						}
					}
				},
				// 稼动率概览配置
				opts2: {
					update: true,
					color: ["#4095E5", "#6AC5C5", '#BD3124'],
					dataLabel: false,
					legend: {
						show: false
					},
					title: {
						show: false,
						name: '',
						fontSize: 0
					},
					subtitle: {
						show: false,
						name: '',
						fontSize: 0
					},
					extra: {
						pie: {
							ringWidth: 50,
							radius: 40,
							label: {
								show: false,
								line: false,
								position: 'outer'
							}
						}
					}
				},
				// 当班报工概览配置
				opts3: {
					update: true,
					color: ["#4095E5", "#6AC5C5", '#BD3124'],
					dataLabel: false,
					legend: {
						show: false
					},
					title: {
						show: false,
						name: '',
						fontSize: 0
					},
					subtitle: {
						show: false,
						name: '',
						fontSize: 0
					},
					extra: {
						pie: {
							ringWidth: 50,
							radius: 40,
							label: {
								show: false,
								line: false,
								position: 'outer'
							}
						}
					}
				},
				// 当班投料概览配置
				opts4: {
					update: true,
					legend: {
						show: false,
						position: "top",
					},
					title: {
						show: true, // 显示标题
						name: '当班投料概览',
						fontSize: 14,
						color: '#333',
						offsetX: 0, // 水平居中
						offsetY: 0
					},
					subtitle: {
						show: false,
						name: '暂无投料数据',
						fontSize: 12,
						color: '#999',
						offsetX: 0,
						offsetY: 20
					},
					yAxis: {
						type: "value",
						min: 0,
						axisLabel: {
							formatter: '{value} KG'
						}
					},
					xAxis: {
						type: "category",
						data: ['物料1', '物料2'], // 默认显示两个类别
						axisLabel: {
							interval: 0,
							rotate: 30,
							fontSize: 10,
							overflow: 'truncate',
							ellipsis: '...'
						}
					},
					series: [{
						label: {
							show: true,
							position: "top",
							formatter: '{c} KG'
						}
					}],
					extra: {
						column: {
							width: 20,
							categoryGap: "20%"
						},
						tooltip: {
							show: false
						}
					}
				}
			}
		},
		methods: {
			shiftChange() {
				this.getChart(this.pageInfo)
				this.getWorkOrderInfo(this.pageInfo)
			},
			shiftTimeChange(val) {
				this.model.shiftId = null;
				this.getShiftList(val);
			},
			getShiftList(shiftTime) {
				fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: getDevice().deviceNo,
					shiftDate: shiftTime ? this.dayjs(shiftTime).format('YYYY-MM-DD') : '',
				}).then((res) => {
					console.log(res, 'resdadarea');
					this.shifts = res.map((item) => ({
						label: item.shift,
						value: item.shiftId,
						id: item.id,
						scheduleDate: item.scheduleDate,
					}));
					if (this.shifts.length !== 0) {
						const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
							item.shiftStartTime,
							item.shiftEndTime));
						console.log(has, 'has');
						if (has)
							this.model.shiftId = has.shiftId;
						else
							this.model.shiftId = this.shifts[0].value;
						if (!shiftTime) {
							this.model.shiftId = this.shifts[0].value;
							this.model.shiftTime = this.dayjs(this.shifts[0].scheduleDate).valueOf();
						}
						this.getChart(this.pageInfo)
						this.getWorkOrderInfo(this.pageInfo)
					} else {
						this.getChart(this.pageInfo)
						this.getWorkOrderInfo(this.pageInfo)
					}
				});
			},
			startWork() {
				uni.showLoading({
					mask: true,
					title: '查询中'
				})
				const that = this;
				fetch('get', '/dms/mobile/startWork', {
					workCode: that.pageInfo.workCode,
				}).then((res) => {
					console.log(res);
					if (res) {
						this.showStart = false;
						this.deviceCodeValidated = null;
						this.moldCodeValidated = null;
						this.deviceCode = null;
						this.moldCode = null;
						this.showConfirmButton = false;
						uni.hideLoading()
						this.$refs.startWorkScanModal.open();
					} else {
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '当前设备有正在生产的工单，无法开始新的工单，请确认！',
							showCancel: false,
							cancelText: '取消',
						});

					}
				}).catch(err => {
					uni.hideLoading()
				})

				// this.open1();
			},
			cancelScan() {
				this.$refs.startWorkScanModal.close();
			},
			// 扫描设备码
			scanDeviceCode() {
				const that = this;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode', 'barCode'],
					success: (res) => {
						that.deviceCode = res.result;
						that.validateDeviceCode();
					},
					fail: (err) => {
						console.log('扫码失败', err);
						that.$toast('扫码失败');
					}
				});
			},

			// 扫描模具码
			scanMoldCode() {
				const that = this;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode', 'barCode'],
					success: (res) => {
						that.moldCode = res.result;
						that.validateMoldCode();
					},
					fail: (err) => {
						console.log('扫码失败', err);
						that.$toast('扫码失败');
					}
				});
			},
			// 验证设备码 - 使用 toUpperCase()
			validateDeviceCode() {
				let scannedCode = String(this.deviceCode).trim().toUpperCase();
				let expectedCode = String(this.workInfo.deviceCode).trim().toUpperCase();
				this.deviceCodeValidated = (scannedCode == expectedCode);
				this.checkIfShowConfirmButton();
			},

			// 验证模具码 - 使用 toLowerCase()
			validateMoldCode() {
				let scannedCode = String(this.moldCode).trim().toLowerCase();
				let expectedCode = String(this.workInfo.moldCode).trim().toLowerCase();
				this.moldCodeValidated = (scannedCode == expectedCode);
				this.checkIfShowConfirmButton();
			},

			// 检查是否显示确认按钮
			checkIfShowConfirmButton() {
				this.showConfirmButton = this.deviceCodeValidated === true && this.moldCodeValidated === true;
				console.log(this.showConfirmButton, 'showConfirmButtonshowConfirmButton');
			},
			getChart(param) {
				this.loading = true;
				const shiftDate = this.dayjs(this.model.shiftTime).format('YYYY-MM-DD');
				fetch('get', '/dms/mobile/workOrderPreviewData', {
					workCode: param.workCode,
					deviceNo: param.deviceNo,
					shiftTime: shiftDate,
					shiftId: this.model.shiftId
				}).then((res) => {
					this.chartData = JSON.parse(JSON.stringify(res || {}));
					this.setChart();
					this.loading = false;
				}).catch(() => {
					this.loading = false;
				});
			},
			setChart() {
				const that = this;
				// 更新图表1数据
				that.chartData1 = {
					series: [{
						data: [{
								name: "已报工数量",
								value: that.chartData.reportQuantity || 0
							},
							{
								name: "未报工数量",
								value: that.chartData.unReportQuantity || 0
							}
						],
						color: ["#4095E5", "#6AC5C5"]
					}]
				};

				// 更新图表2数据
				that.chartData2 = {
					series: [{
						data: [{
								name: "实际开工时长",
								value: that.chartData.actualOpenTime || 0
							},
							{
								name: "异常停机时长",
								value: that.chartData.errorStopTime || 0
							}
						],
						color: ["#4095E5", "#6AC5C5"]
					}]
				};

				// 更新图表3数据
				that.chartData3 = {
					series: [{
						data: [{
								name: "合格品数量",
								value: that.chartData.passCount || 0
							},
							{
								name: "不良品数量",
								value: that.chartData.failCount || 0
							},
							{
								name: "报废品数量",
								value: that.chartData.scrapCount || 0
							}
						],
						color: ["#4095E5", "#6AC5C5", "#BD3124"]
					}]
				};

				// 更新图表4数据
				if (this.chartData.currentFeedingList && this.chartData.currentFeedingList.length > 0) {
					const displayItems = this.chartData.currentFeedingList.slice(0, 2);
					const materialNames = displayItems.map(item =>
						item.materialName && item.materialName.length > 4 ?
						item.materialName.substring(0, 3) + '...' :
						item.materialName
					);

					this.chartData4.categories = materialNames;
					this.opts4.xAxis.data = materialNames;
					this.chartData4.series[0].data = displayItems.map(item => item.theoryWeight || 0);
					this.chartData4.series[1].data = displayItems.map(item => item.weight || 0);
				} else {
					this.chartData4.categories = ['暂无数据', ''];
					this.chartData4.series[0].data = [null];
					this.chartData4.series[1].data = [null];
					this.opts4.xAxis.data = [];
				}
			},
			showFeedingCount() {
				this.$refs.feedingModal.open();
			},
			getWorkOrderInfo(param) {
				this.loading = true;
				const shiftDate = this.dayjs(this.model.shiftTime).format('YYYY-MM-DD');
				Promise.all([
					fetch('get', '/dms/mobile/selectWorkByWorkCode', {
						workCode: param.workCode,
						deviceNo: param.deviceNo
					}),
					fetch('get', '/dms/mobile/workOrderRepostInfo', {
						workCode: param.workCode,
						deviceNo: param.deviceNo,
						shiftTime: shiftDate,
						shiftId: this.model.shiftId
					})
				]).then(([workRes, numberRes]) => {
					this.$set(this, 'workInfo', workRes || {});
					console.log(this.workInfo, 'workInfo');
					this.state = workRes.state;
					this.$set(this, 'workNumberInfo', numberRes || {});
					console.log(this.workNumberInfo, 'workNumberInfo');
					this.loading = false;
				}).catch(() => {
					this.loading = false;
				});
			},
			openCuttingPlan() {
				this.$refs['modalCuttingPlan'].open(this.workInfo.cuttingPlanCode);
			},
			openModalPrintLabel(item) {
				this.$refs['modalPrintLabel'].open(item);
			},
			open1() {
				this.$refs.popup1.open()
			},
			open2() {
				this.$refs.popup2.open()
			},
			open3() {
				this.$refs.popup3.open()
			},
			open4() {
				this.$refs.popup4.open()
			},
			openMaterial() {
				uni.navigateTo({
					url: '/pages/workbench/material/form/index?workCode=' + this.workInfo.workCode
				})
			},
			openReport() {
				uni.navigateTo({
					url: '/pages/workbench/report/form/index?workOrder=' + this.workInfo.workCode
				})
			},
			openScrap() {
				uni.navigateTo({
					url: '/pages/workbench/inspect/form/index?workCode=' + this.workInfo.workCode
				})
			},
			openShutdown() {
				uni.navigateTo({
					url: '/pages/workbench/shutdown/index?workCode=' + this.workInfo.workCode
				})
			},
			toClear() {
				uni.navigateTo({
					url: '/pages/workbench/clear/form/index?workCode=' + this.workInfo.workCode +
						'&productionProcessesNum=' + this.workInfo.productionProcessesNum
				})
			},
			confirm1() {
				fetch('put', '/dms/mobile/startProduce', {
					flag: 'false',
					workCode: this.workInfo.workCode,
				}).then(() => {
					this.$toast('工单开始执行');
					this.state = null;
					this.getWorkOrderInfo(this.pageInfo);
					this.getChart(this.pageInfo);
					this.$refs.startWorkScanModal.close();
				});
			},
			confirm2() {
				const workCode = String(this.workInfo.workCode);
				fetch('put', '/dms/mobile/produceFinish', {
					workCode
				}, null, null, true, true).then((res) => {
					if (res.code == "1" && res.msg) {
						uni.showModal({
							title: '提示',
							content: res.msg,
							showCancel: true,
							cancelText: '取消',
							confirmText: '强制完成',
							confirmColor: '#FF0000', // 设置确认按钮文字颜色为红色
							success: (modalRes) => {
								if (modalRes.confirm) {
									fetch("put", "/dms/mobile/produceFinish", {
										workCode,
										mandatoryEnd: true
									}, null).then((finalRes) => {
										this.$toast('工单执行完成');
										this.getWorkOrderInfo(this.pageInfo);
										this.getChart(this.pageInfo);
									}).catch((err) => {});
								}
							}
						});
					} else {
						this.$toast('工单执行完成');
						this.getWorkOrderInfo(this.pageInfo);
						this.getChart(this.pageInfo);
					}
				});
			},
			confirm3() {
				fetch('put', '/dms/mobile/interrupt', {
					workCode: this.workInfo.workCode,
					interruptReason: this.interruptReason,
				}).then(() => {
					this.$toast('工单中断成功');
					this.state = null;
					this.getWorkOrderInfo(this.pageInfo);
					this.getChart(this.pageInfo);
				});
			},
			confirm4() {
				fetch('put', '/dms/mobile/restoreInterrupt', {
					workCode: this.workInfo.workCode,
				}).then(() => {
					this.$toast('工单恢复成功');
					this.state = null;
					this.getWorkOrderInfo(this.pageInfo);
					this.getChart(this.pageInfo);
				});
			},
			goto(url) {
				uni.redirectTo({
					url,
					animationType: "pop-in",
					animationDuration: 1000,
				})
			},
			getInterruptReasons() {
				fetch("get", "/dms/faultCategory/dictList", {
					name: "中断原因",
				}).then((res) => {
					this.interruptReasons = res.map(item => {
						return {
							label: item.value,
							value: item.value
						}
					});
					if (this.interruptReasons.length !== 0)
						this.interruptReason = this.interruptReasons[0].value;
				});
			}
		},
		onLoad(params) {
			this.pageInfo = params
			this.state = params.state || null;
			// this.flag = params.flag || null;
			this.getWorkOrderInfo(this.pageInfo);
			this.shiftTimeChange(this.model.shiftTime)
			// this.getChart(this.pageInfo);
			this.getInterruptReasons()
		}
	};
</script>

<style scoped lang="scss">
	.left {
		flex: 0 auto;
		width: 50rem;
		background: #f8f8fa;
	}

	.right {
		flex: 1;
		background: #fff;
		display: flex;
		flex-direction: column;
		padding: 2rem;

		.loading-container {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 500rpx;
		}

		.charts-container {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			margin-bottom: 2rem;

			.chart-item {
				width: 48%;
				margin-bottom: 1.5rem;
				padding: 1rem 2rem;
				border-radius: 4px;
				display: flex;
				height: 40rem;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
				background: #fff;

				.chart-left {
					width: 50%;
					height: 100%;
					display: flex;
					flex-direction: column;

					.chart-title {
						color: #333;
						font-weight: bold;
						margin-bottom: 10px;
						text-align: left;
						font-size: 10rpx;
					}

					.chart-qiun-data-charts {
						height: 32rem;
						width: 28rem;
					}
				}

				.chart-right {
					width: 50%;
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					padding-top: 5rem;

					.percentage-text {
						display: flex;
						padding-left: 10px;
						margin-top: 3rem;
						font-size: 2.5rem;

						.percentage-label {
							width: 70%;
							margin-right: 4rem;
						}

						.percentage-value {
							font-weight: 700;
						}
					}

					.chart-legend {
						display: flex;
						flex-direction: column;
						padding-left: 10px;

						.legend-item {
							display: flex;
							align-items: center;
							gap: 8px;
							margin-bottom: 8px;

							.legend-color {
								width: 12px;
								height: 12px;
								border-radius: 2px;
								margin-right: 1rem;
							}

							.legend-text {
								display: flex;
								justify-content: space-between;
								width: 100%;

								.legend-label {
									color: #666;
								}

								.legend-value {
									font-weight: bold;
									color: #333;
								}
							}
						}
					}
				}
			}
		}

		.btn-group {
			display: flex;
			flex-wrap: nowrap;
			justify-content: center;
			gap: 12px;
			padding: 16px 0;
			width: 100%;
			overflow-x: auto;

			.btn-item {
				flex: 1 0 auto;
				margin: 0 5rpx;
				min-width: 80px;
				max-width: 100px;
				height: 44px;
				font-size: 14px;
				border-radius: 6px;
				font-weight: 500;
				display: flex;
				align-items: center;
				justify-content: center;
				white-space: nowrap;
				cursor: pointer;
				transition: all 0.2s ease;
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

				&:hover {
					transform: translateY(-1px);
					box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
				}

				&:active {
					transform: translateY(1px);
					box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
				}

				text {
					color: inherit;
					font-weight: inherit;
				}
			}

			.btn-default {
				background-color: #f5f7fa;
				color: #4a5568;
				border: 1px solid #e2e8f0;

				&:hover {
					background-color: #edf2f7;
					border-color: #cbd5e0;
				}
			}

			.btn-primary {
				background-color: #3182ce;
				color: white;

				&:hover {
					background-color: #2b6cb0;
				}
			}

			.btn-success {
				background-color: #48bb78;
				color: white;

				&:hover {
					background-color: #38a169;
				}
			}

			.btn-danger {
				background-color: #e53e3e;
				color: white;

				&:hover {
					background-color: #c53030;
				}
			}
		}
	}

	.line-search {
		display: flex;
		align-items: center;
	}

	.serch-line {
		width: 7rem;
		font-size: 2.5rem;
		margin-right: 10px;
	}

	.scan-form {
		padding: 10px 0;
	}

	.form-item {
		margin-bottom: 20px;
	}

	.form-label {
		font-size: 2.8rem;
		color: #333;
		margin-bottom: 8px;
	}

	.form-input-group {
		display: flex;
		align-items: center;
	}

	.form-input {
		flex: 1;
		height: 44px;
		padding: 0 12px;
		border: 1px solid #e2e8f0;
		border-radius: 6px 0 0 6px;
		font-size: 2.8rem;
	}

	.scan-btn {
		width: 120px;
		height: 44px;
		background-color: #3182ce;
		color: white;
		text-align: center;
		line-height: 44px;
		font-size: 2.8rem;
		border-radius: 0 6px 6px 0;
		cursor: pointer;
	}

	.validation-result {
		margin-top: 8px;
		font-size: 2.4rem;
	}

	.valid {
		color: #48bb78;
	}

	.invalid {
		color: #e53e3e;
	}

	.custom-buttons {
		display: flex;
		justify-content: center;
		margin-top: 40rpx;

		.cancel-btn,
		.confirm-btn {
			flex: 0 0 20%;
			height: 8rem;
			line-height: 8rem;
			border-radius: 8rpx;
			font-size: 4rem;
			text-align: center;
			cursor: pointer;
			transition: all 0.3s ease;
			margin-right: 5rem;
		}

		.cancel-btn {
			background-color: #f5f5f5;
			color: #666;

			&:active {
				background-color: #e0e0e0;
			}
		}

		.confirm-btn {
			background-color: #409eff;
			color: #fff;

			&:active {
				background-color: #3a8ee6;
			}
		}
	}
</style>